﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Way.Contract.MVC;
using Way.Bus.WMS.Model;
using Way.Contract;
using System.Data;
using Way.Bus.Controllers;
using Way.EAP.DataAccess.Entity;
using Way.Bus.WMS.Controllers;
using Way.Contract.Center;
using Way.EAP.DataAccess.Data;
using Way.EAP.DataAccess.Regulation;
using Way.Contract.Data;
using Way.Bus.WMS.ST.Model;
using Way.Bus.Model;
using Way.Contract.Data.ControllerData;

namespace Way.Bus.WMS.ST.Controllers.OutOrder
{
    public class ST_OutNoticeController : StockOutNoticeController
    {   
        //构造方法 controller与model绑定
        public ST_OutNoticeController()
            : base(new ST_OutNotice())
        {
        }
        public ST_OutNoticeController(IModel model) : base(model) { }

        //controller 对应的html页面
        protected override string OnGetPath()
        {
            return "Views/ST/OutOrder/OutNotice.htm";
        }

        protected override string OnControllerName()
        {
            return "发货通知";
        }

        protected override string OnGetControllerDescription()
        {
            return "发货通知";
        }
        #region 页面设置
        
        /// <summary>
        /// 禁用审核
        /// </summary>
        public override bool IsReviewedState
        {
            get
            {
                return false;
            }
        }

        /// <summary>
        /// 启用提交
        /// </summary>
        /// 
    
        public override bool  IsSubmit
        {
            get
            {
                return true;
            }
        }
       
        

        public override bool IsClearAway
        {
            get
            {
                return false;
            }
        }

        //禁用打印
        public override bool IsPrint
        {
            get
            {
                return true;
            }
        }
        #endregion 

        #region 初始化方法
        public static void InitOutNotice(ModelData data, ItemData item)
        {
            if (data.name.EndsWith("OutNotice"))
            {
                data.title = "发货通知单";
                if (item.IsField("ClientContactPerson") || item.IsField("ClientPhoneCode"))
                {
                    item.required = true;
                }
                switch (item.field.ToLower())
                {
                    case "sourcecode":
                    case "officeworker":
                    case "stocktype":
                    case "isdisable":
                    case "sourcename":
                    case "reviewedby":
                    case "revieweddate":
                    case "isreviewed":
                    case "receiptprintnum":
                    case "receiptprintstate":
                    case "sourceoutcode":
                    case "finishtime":
                    case "rowindex":
                        item.visible = false;
                        break;

                    case "code":
                        item.title = "发货单号";
                        item.index = 1;
                        item.disabled = true;
                        break;

                    case "workerid":
                        item.visible = false;
                        break;

                    case "bumen":
                        item.title = "部门";
                        item.index = 3;
                        item.visible = false;
                        break;

                    case "clientno":
                        item.title = "供货客户";
                        item.index = 4;
                        break;

                    case "clientcontactperson":
                        item.title = "供货客户联系人";
                        item.index = 5;
                        item.foreign.rowdisplay.Add("LXRPhone", "clientphonecode");
                        //item.foreign.rowdisplay.Add("LXRAddress", "receiptaddress");
                        break;

                    case "clientphonecode":
                        item.title = "供货客户联系电话";
                        item.index = 6;
                        break;

                    case "receiptclient":
                        item.title = "收货客户";
                        item.index = 7;
                        break;

                    case "receiptaddress":
                        item.title = "收货地址";
                        item.index = 8;
                        break;

                    case "remark":
                        item.index = 9;
                        break;

                    case "receiptperson":
                        item.index = 10;
                        break;

                    case "receiptphonecode":                        
                        item.index = 11;
                        break;

                    case "state":
                        item.title = "状态";
                        item.index = 12;
                        item.disabled = true;
                        break;

                    case "outtime":
                        item.title = "发货时间";
                        item.index = 13;
                        break;

                    case "noticeprintstate":
                        item.title = "打印状态";
                        item.index = 13;
                        item.disabled = true;
                        break;

                    case "noticeprintnum":
                        item.title = "打印次数";
                        item.index = 14;
                        item.disabled = true;
                        break;

                    case "towhno":
                        item.required = true;
                        break;
                }
                if (item.IsField("ISSQE"))
                    item.visible = true;
            }
        }
        public static void InitOutNoticeMaterials(ModelData data, ItemData item)
        {
            if (data.name.EndsWith("StockOutNoticeMaterials"))
            {
                data.title = "发货通知单明细";
                switch (item.field.ToLower())
                {
                    case "parentid":
                    case "sourcecode":
                    case "state":
                    case "isdisable":
                    case "code":
                    case "createdby":
                    case "creationdate":
                    case "submitedby":
                    case "issubmited":
                    case "submiteddate":
                    case "reviewedby":
                    case "revieweddate":
                    case "isreviewed":
                    case "funitid":
                    case "singleweight":
                    case "mweight":
                        item.visible = false;
                        break;

                    case "finishnum":
                        item.title = "出库数量";
                        item.disabled = true;
                        break;

                    case "staynum":
                        item.title = "待出库数量";
                        item.disabled = true;
                        break;

                    case "fmodel":
                        item.disabled = true;
                        break;

                    case "materialcode":
                        item.title = "货物名称";
                        if (item.foreign != null)
                        {
                            item.foreign.rowdisplay.Add("FMODEL", "FMODEL");
                            item.foreign.rowdisplay.Add("CODE", "MCODE");
                        }
                        item.index = 5;
                        break;

                    case "mcode":
                        item.title = "货物编码";
                        item.disabled = true;
                        break;

                    case "receiptcode":
                        item.visible = true;
                        break;

                    case "num":
                        item.title = "发货数量";
                        item.index = 6;
                        break;
                    case "batchno":
                        item.index=7;
                        break;
                }
            }
         }
        /// <summary>
        /// 初始化显示与否
        /// </summary>
        /// <param name="data"></param>
        /// <param name="item"></param>
        protected override void OnInitViewChildItem(ModelData data,ItemData item)
        {
            if (item.IsField("rowindex"))
            {
                item.isedit = false;
            }
            InitOutNotice(data, item);
            InitOutNoticeMaterials(data, item);
        }

        [ActionCommand(name = "导入", title = "导入", index = 6, icon = "icon-down", isselectrow = false, editshow = true, onclick = "import3")]
        public void ImportExcel()
        {

        }

        [ActionCommand(name = "导出", title = "导出", index = 10, icon = "icon-down", isselectrow = false, onclick = "emport3")]
        public void Emport()
        {
            //ExcelDRController er = new ExcelDRController();
            //er.bc = this;
        }

        // [ActionCommand(name = "生成出库单", title = "生成出库单", index =6, icon = "icon-add", isselectrow = true)]
        public void OnCreateOutOrder()
        {
           
            List<ControllerAssociate> listAssociate = new List<ControllerAssociate>();
            //出库通知单与出库单关联
            RelationOrder(listAssociate);
            ControllerAssociate ca=listAssociate[0];
            StockOutOrder oo = this.OnConvertItem(ca, this.ActionItem) as StockOutOrder;
            //infoMaterial(oo);
            oo.Creationdate = DateTime.Now;
            BillNumberController bnc = new BillNumberController();
            oo.Code = bnc.GetBillNo(new ST_OutOrderController());
            EntityList<StockOutOrder> list = new EntityList<StockOutOrder>(this.model.GetDataAction());
            list.Add(oo);
            list.Save();

        }
        #endregion


        #region 重写方法
        protected override string OnPrinting(ControllerBase.PrintEvent item)
        {
            String rs = base.OnPrinting(item);
            ST_OutNotice son = item.Item as ST_OutNotice;
            son.NoticePrintNum = son.NoticePrintNum + 1;
            son.NoticePrintState = true;
            EntityList<ST_OutNotice> list = new EntityList<ST_OutNotice>(this.model.GetDataAction());
            list.Add(son);
            list.Save();
            return rs;
        }
        protected override void OnForeignIniting(IModel model, InitData data)
        {
            if (this.fdata.foreignobject.EndsWith("Materials"))
            {
                //序号、编码code、名称FNAME、全名FFULLNAME、大类ClassID，基本计量单位FUNITID、批次管理BATCH、状态STATUS、是否迅速超出ISOVERIN是否禁用IsDisable、是否质检ISCHECKPRO、备注Remark
                if (this.fdata.filedname == "MATERIALCODE")
                {
                    foreach (ItemData d in data.modeldata.childitem)
                    {
                        Way.Bus.WMS.ST.Controllers.Custemer.MaterialsController.InitMaterials(data.modeldata, d);
                    }
                    return;
                }
            }
        }
        protected override void OnForeignLoading(IModel model, Way.Contract.Data.ControllerData.loadItem item)
        {
            List<SQLWhere> list = new List<SQLWhere>();
            //物流公司与客户是同一张表，ftype=1是物流公司 ftype=2是客户
            if (base.fdata.filedname == "CLIENTNO")
            {
                list.AddRange(item.whereList);
                SQLWhere w = new SQLWhere();
                w.ColumnName = "ftype";
                w.Value = "2";
                list.Add(w);
                item.whereList = list.ToArray();
            }
            if (this.fdata.filedname == "CLIENTCONTACTPERSON")//以前供货商联系人字段为RECEIPTCONTACTPERSON
            {
                if (this.ActionItem["CLIENTNO"] != null && !string.IsNullOrEmpty(this.ActionItem["CLIENTNO"].ToString()))
                {
                    list.AddRange(item.whereList);
                    SQLWhere w = new SQLWhere();
                    w.ColumnName = "PID";
                    w.Value = this.ActionItem["CLIENTNO"].ToString();
                    list.Add(w);
                    item.whereList = list.ToArray();
                }
                else
                    throw new Exception("请先选择客户");
            }
        }
        protected override ReadTable OnForeignLoad(IModel model, loadItem item)
        {
            if (this.fdata.foreignobject.EndsWith("Materials"))
            {
                if (this.fdata.filedname == "MATERIALCODE")
                {
                    if (this.ActionItem["CLIENTNO"] != null && !string.IsNullOrEmpty(this.ActionItem["CLIENTNO"].ToString()))
                    {
                        item.rowsql = Common.GetNoticeMaterialsSQL(item.rowsql, this.ActionItem["CLIENTNO"].ToString());
                    }
                    else
                        throw new Exception("请先选择客户");
                }
            }
            return base.OnForeignLoad(model, item);
        }
        /// <summary>
        /// 添加不同类型
        /// </summary>
        /// <param name="item"></param>
        /// <param name="stockType"></param>
        public virtual int SetStockType()
        {
            return 0;
        }

       

        /// <summary>
        /// 查询按钮，并添加查询条件
        /// </summary>
        /// <param name="m"></param>
        /// <param name="where"></param>

        protected override void OnGetWhereing(IModel m, List<SQLWhere> where,loadItem item)
        {
            base.OnGetWhereing(m, where, item);
        }

        protected override void OnAdding(ControllerBase.SaveEvent item)
        {
            Merger(item);
            //item.Item = GetStockNum(item.Item as ST_OutNotice);
            base.OnAdding(item);
        }

        protected ST_OutNotice GetStockNum(ST_OutNotice ston)
        {
            foreach (StockOutNoticeMaterials item in ston.Materials)
            {
                string strSqlWhere = "Code='" + item.MATERIALCODE + "'";
                if (!string.IsNullOrEmpty(item.BATCHNO))
                    strSqlWhere += " and BATCHNO='" + item.BATCHNO + "'";
                EntityList<StockInfoMaterials> soo = new EntityList<StockInfoMaterials>(this.model.GetDataAction());
                soo.GetData(strSqlWhere);
                if (soo.Count > 0) {
                    double tempnum = 0;
                    foreach (StockInfoMaterials itemsoo in soo)
                    {
                        tempnum += itemsoo.NUM;
                    }
                    item.KCNUM = tempnum;
                }
                else
                    item.KCNUM = 0;
            }
            return ston;
        }
        protected override void OnEditing(ControllerBase.SaveEvent item)
        {
            Merger(item);
            //item.Item = GetStockNum(item.Item as ST_OutNotice);
            base.OnEditing(item);
        }

        protected override void  OnRemoveing(ControllerBase.SaveEvent item)
        {
            isExistOutOrder(item);
            base.OnRemoveing(item);
        }

        protected override void OnRemoveed(EntityBase item)
        {
            //deleteOutOrder(item);
            base.OnRemoveed(item);
        }

        protected override void OnSubmitData(BasicInfo info)
        {
            ST_OutNotice sin = info as ST_OutNotice;
            sin.Materials.DataAction = this.model.GetDataAction();
            sin.Materials.GetData();

            if (sin.Materials.Count == 0)
            {
                throw new Exception("单据无明细数据不能提交！");
            }
            List<StockOutNoticeMaterials> sonmList = new List<StockOutNoticeMaterials>();
            for (int i = 0; i < sin.Materials.Count; i++)
            {
                sonmList.Add(sin.Materials[i]);
            }
            for (int i = 0; i < sonmList.Count; i++)
            {
                StockOutNoticeMaterials temp = sonmList[i];
                bool resultbl = false;
                for (int l = 0; l < sin.Materials.Count; l++)
                {
                    if (sin.Materials[l].MATERIALCODE == temp.MATERIALCODE && resultbl == true) {
                        EntityList<Materials> soo = new EntityList<Materials>(this.model.GetDataAction());
                        soo.GetData("ID='" + temp.MATERIALCODE + "'");
                        if (soo.Count>0)
                            throw new Exception("明细产品 '" + soo[0].FNAME + "' 出现重复行，请手动合并！");
                    }
                    if (sin.Materials[l].MATERIALCODE == temp.MATERIALCODE && resultbl == false)
                        resultbl = true;
                }
            }
            try
            {
                base.OnSubmitData(info);
               // OnCreateOutOrder();
                //setStatus(info);
            }
            catch (Exception ex)
            {
                //base.OnUnSubmitData(info);
                throw ex;
            }
        }

        protected override void OnUnSubmitData(Bus.Model.BasicInfo info)
        {
            isSubmitedStatus(info);
            base.OnUnSubmitData(info);
        }

        //设置出库通知状态：3、生成出库通知
        public void setStatus(EntityBase item)
        {
            ST_OutNotice notice = item as ST_OutNotice;
            IDataAction action = this.model.GetDataAction();
            try
            {
                //从数据库查询入库情况
                string sql = "update "+ notice.ToString() +" set STATE='3' where ID = '" + notice.ID + "'";
                action.Execute(sql);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        //判断出库通知对应的出库单是否存在，若存在则提醒客户不允许操作
        public void isExistOutOrder(ControllerBase.SaveEvent item)
        {
            bool bl = false;
            StockOutNotice son = item.Item as StockOutNotice;
            EntityList<StockOutOrder> soo = new EntityList<StockOutOrder>(this.model.GetDataAction());
            soo.GetData("SourceID='" + son.ID + "'");
            if (soo.Count != 0)
            {
                throw new Exception("操作失败，该出库通知单存在对应的出库单！请在删除出库单后，再对该出库通知单进行操作。");
            }
        }

        //获得出库单的提交状态，如果已提交，则提示“出库通知不能撤销提交”
        public void isSubmitedStatus(Bus.Model.BasicInfo info)
        {
            IDataAction action = this.model.GetDataAction();
            string sqlSelect = "select IsSubmited from Acc_WMS_OutOrder " +
                               "where SourceID = '" + info.ID + "' ";
            DataTable oldDataTable = action.GetDataTable(sqlSelect);
            foreach (DataRow oldRow in oldDataTable.Rows)
            {
                if (Convert.ToBoolean(oldRow["IsSubmited"]))
                {
                    throw new Exception("异常：出库单已提交，因此出库通知不能撤销提交！");
                }
                else
                {
                    throw new Exception("异常：出库单已存在，如需撤销出库通知，请先删除对应的出库单信息！");
                }
            }
        }

        //删除出库通知单的同时，删除出库单及明细
        public void deleteOutOrder(EntityBase item)
        {
            ST_OutNotice notice = item as ST_OutNotice;
            try
            {
                //string sql = "delete from Acc_WMS_OutOrder  where SourceCode = '" + notice.SourceCode + "'";
                //this.model.GetDataAction().Execute(sql);
                //sql = "delete from Acc_WMS_OutOrderMaterials  where SourceCode = '" + notice.SourceCode + "'";
                //this.model.GetDataAction().Execute(sql);

                StockOutOrder oo = new StockOutOrder();
                String sql = "Delete  from " + oo.ToString() + " where SourceId=" + notice.ID;
                String sql2 = "Delete  from " + ((IHierarchicalEntityView)oo.Materials).ChildEntity.ToString() + " where SourceId=" + notice.ID;
                this.model.GetDataAction().StartTransation();
                this.model.GetDataAction().Execute(sql);
                this.model.GetDataAction().Execute(sql2);
                this.model.GetDataAction().EndTransation();
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// 设置按钮显示名称
        /// </summary>
        /// <param name="commands"></param>
        /// <returns></returns>
        protected override ActionCommand[] OnInitCommand(ActionCommand[] commands)
        {
            ActionCommand[] coms = base.OnInitCommand(commands);
            //获取所有按钮集合
            foreach (ActionCommand ac in coms)
            {
                if (ac.command == "SubmitData")
                {
                    ac.title = "提交后数据不能修改";
                }
                if (ac.command == "UnSubmitData")
                {
                    ac.visible = true;
                }
            }
            return coms;
        }

       
        /// <summary>
        /// 出库通知单删除时验证此方法
        /// </summary>
        protected override void Remove()
        {
            if (this.ActionItem != null)
            {
                BasicInfo info = getinfo(this.ActionItem["id"].ToString());
                if (info != null)
                {
                    EntityList<StockOutOrder> sio = new EntityList<StockOutOrder>(this.model.GetDataAction());
                    sio.GetData("sourcecode='" + info.Code + "'");
                    if (sio.Count == 0)
                    {
                        try
                        {
                            this.modelList.Add(this.ActionItem);
                            this.modelList.Remove(this.ActionItem);
                            this.modelList.Save();
                        }
                        finally
                        {
                            this.modelList.Clear();
                        }
                    }
                    else
                    {
                        throw new Exception("单据不能删除，该单据已在下游单据中存在！");
                    }
                }

            }
        }
        //通知单下推，选择其他原单时改变待入库明细的数据
        [WhereParameter]
        public string NoticeId { get; set; }
        public virtual string GetNoticeStayGrid()
        {
            EntityList<StockOutNoticeMaterials> List1 = new EntityList<StockOutNoticeMaterials>(this.model.GetDataAction());
            EntityList<StockOutNotice> soList = new EntityList<StockOutNotice>(this.model.GetDataAction());
            soList.GetData("code='" + NoticeId + "'");
            List1.GetData("parentId='" + soList[0].ID + "'");
            List<StockOutNoticeMaterials> list = new List<StockOutNoticeMaterials>();
            list = List1;
            string str = JSON.Serializer(list.ToArray());
            return str;
        }
       

        /// <summary>
        /// 指定下推对象
        /// </summary>
        /// <returns></returns>
        public virtual ControllerBase PushController()
        {
            return new ST_OutOrderController();
        }
        #endregion

        #region 下推
        /// <summary>
        /// 禁用下推
        /// </summary>
        public override bool IsPushDown
        {
            get
            {
                return true;
            }
        }
        /// <summary>
        /// 单据转换（点击下推按钮）
        /// </summary>
        /// <param name="ca"></param>
        /// <param name="actionItem"></param>
        /// <returns></returns>
        protected override EntityBase OnConvertItem(ControllerAssociate ca, EntityBase actionItem)
        {
            //下推前判断
            WMShelp.IsPush(this);
            ST_OutNotice cd = actionItem as ST_OutNotice;
            cd.Materials.DataAction = this.model.GetDataAction();
            cd.Materials.GetData();//获取子集的数据
            bool isconvert = false;
            foreach (StockOutNoticeMaterials sonm in cd.Materials)
            {
                if (sonm.STAYNUM > 0)
                {
                    isconvert = true;
                }
            }
            if (!isconvert)
                throw new Exception("异常：通知单已全部操作完毕不能下推！");
            EntityBase eb = base.OnConvertItem(ca, actionItem);
            //  if (ca.cData.name.EndsWith(GetThisController()))
            eb = PushInOrder(eb, cd);//下推
            eb["Remark"] = actionItem["Remark"];
            return eb;
        }

        //获得仓库信息
        public int getTOWHNO(Bus.Model.BasicInfo info)
        {
            ST_OutNotice cd = info as ST_OutNotice;

            int TOWHNO = 0;
            IDataAction action = this.model.GetDataAction();
            string sqlSelect =  "select t1.MCODE, t1.WAREHOUSEID, t2.WAREHOUSENAME " +
                                "from Acc_WMS_InfoMaterials t1 " +
                                "left join Acc_WMS_WareHouse t2 " +
                                "on t1.WAREHOUSEID = t2.ID " +
                                "where t1.MCODE = '" + cd.Materials[0].MCODE + "' ";
            DataTable oldDataTable = action.GetDataTable(sqlSelect);
            if (oldDataTable.Rows.Count > 0)
            {
                TOWHNO = Convert.ToInt16(oldDataTable.Rows[0]["WAREHOUSEID"]);
            }

            return TOWHNO;
        }

        /// <summary>
        /// 下推判断
        /// </summary>
        /// <param name="eb"></param>
        /// <param name="cd"></param>
        /// <returns></returns>
        protected virtual EntityBase PushInOrder(EntityBase eb, ST_OutNotice cd)
        {
            if (eb is StockOutOrder)
            {
                StockOutOrder ebin = eb as StockOutOrder;
                string sourceCode = eb.GetAppendPropertyKey("SOURCECODE");
                ebin[sourceCode] = ebin.GetForeignObject<StockOutNotice>(this.model.GetDataAction()).Code;
                string cname = eb.GetAppendPropertyKey("CLIENTNO");
                string ccname = cd.GetAppendPropertyKey("CLIENTNO");
                ebin.CLIENTNO = cd.CLIENTNO;
                ebin[cname] = cd[ccname];

                ebin.STATE = 0;
                ebin.STOCKTYPE = SetStockType();
                ebin.IsSubmited = false;
                ebin.IsReviewed = false;
                ebin.SourceID = cd.ID;
                ebin.SourceController = this.ToString();
                ebin.Code = new BillNumberController().GetBillNo(this) ;
                ebin.TOWHNO = getTOWHNO(cd);
                ebin[ebin.GetAppendPropertyKey("Createdby")] = "";
                ebin[ebin.GetAppendPropertyKey("Submitedby")] = "";
                ebin.Submiteddate = DateTime.MinValue;
                ebin.Creationdate = DateTime.MinValue;
                ebin.Reviewedby = "";
                ebin.Revieweddate = DateTime.MinValue;
                ebin.Modifiedby = "";
                ebin.Modifieddate = DateTime.MinValue;
                //ebin.STAY3 = cd.OutRule;///将出库规则赋值到stay3上
                ebin.StayMaterials.DataAction = this.model.GetDataAction();
                int id = ebin.GetForeignObject<StockOutNotice>(this.model.GetDataAction()).ID;
                ebin.StayMaterials.GetData("ParentId=" + id + "");
                //销售出库通知单重写此方法
                SellOutOrder(ebin,cd);
                #region 下推转换明细方法暂时不要
                //初始化货位信息
                //for (int i = 0; i < ebin.Materials.Count; i++)
                //{
                //    if ((cd.Materials.Count-1) >= i)
                //    {
                //        ebin.Materials[i].BATCHNO = cd.Materials[i].BATCHNO;
                //        ebin.Materials[i].DEPOTWBS = getDEPOTWBS(ebin.Materials[i].MCODE, ebin.Materials[i].BATCHNO);
                //    }
                //}
                //foreach (StockOutOrderMaterials m in ebin.Materials)
                //{
                //    m.NUM = m.NUM - m.GetSourceNum(m.SourceTable, m.SourceRowID, m.MATERIALCODE, ebin.ID);
                //}
                //ebin.Materials.RemoveAll(delegate(StockOutOrderMaterials m)
                //{
                //    return m.NUM <= 0;
                //});

                //if (ebin.Materials.Count <= 0)
                //{
                //    throw new Exception("下推完成不能重复下推");
                //}
                #endregion
                eb = ebin;
            }
            return eb;
        }

        /// <summary>
        /// 只有销售出库通知单重写此方法
        /// </summary>
        /// <param name="ebin"></param>
        protected virtual void SellOutOrder(StockOutOrder ebin, ST_OutNotice cd)
        {
            
        }

        /// <summary>
        /// 根据MCODE获得货位信息
        /// </summary>
        /// <param name="ebin"></param>
        protected virtual string getDEPOTWBS(string mcode,string batchno)
        {
            string DEPOTWBS = "";
            IDataAction action = this.model.GetDataAction();
            string sqlSelect =  "select t1.MCODE,t1.BATCHNO,t1.DEPOTWBS,t2.WAREHOUSENAME, t1.WAREHOUSEID,t3.WAREHOUSENAME "+
                                "from Acc_WMS_InfoMaterials t1  "+
                                "left join Acc_WMS_WareHouse t2 "+
                                "on t1.DEPOTWBS = t2.ID "+
                                "left join Acc_WMS_WareHouse t3 "+
                                "on t1.WAREHOUSEID = t3.ID "+
                                "where MCODE = '"+ mcode + "' "+
                                "and t1.BATCHNO = '" + batchno + "' ";
            DataTable oldDataTable = action.GetDataTable(sqlSelect);
            if (oldDataTable.Rows.Count > 0)
            {
                DEPOTWBS = oldDataTable.Rows[0]["DEPOTWBS"].ToString();
            }
            return DEPOTWBS;
        }

        /// <summary>
        /// 单据转换（建立关联关系）
        /// </summary>
        /// <returns></returns>
        protected override ControllerAssociate[] DownAssociate()
        {
            List<ControllerAssociate> list = new List<ControllerAssociate>();
            //出库通知单与出库单关联
            RelationOrder(list);
            return list.ToArray();
        }

        /// <summary>
        /// 出库通知单与入库通知单关联
        /// </summary>
        /// <param name="list"></param>
        public virtual void RelationOrder(List<ControllerAssociate> list)
        {
            //控制器转换器出库通知单-出库单

            ControllerAssociate b2 = new ControllerAssociate(this, PushController());

            //单据属性映射
            PropertyMap mapORDERID1 = new PropertyMap();
            ///单号ID --来源单号
            mapORDERID1.TargerProperty = "SourceCode";
            mapORDERID1.SourceProperty = "Code";
            b2.Convert.AddPropertyMap(mapORDERID1);

            PropertyMap map17 = new PropertyMap();//发货时间
            map17.SourceProperty = "OutTime";
            map17.TargerProperty = "INOUTTIME";
            b2.Convert.AddPropertyMap(map17);
            #region 下推转换明细方法暂时不要
            //实体类型转换器（出库通知单-出库单）
            //ConvertAssociate nTo = new ConvertAssociate();
            //nTo.SourceType = typeof(StockOutNoticeMaterials);//下推来源单据子集
            //nTo.TargerType = typeof(StockOutOrderMaterials);//下推目标单据子集
            //YS(nTo);
            //b2.AddConvert(nTo);
            #endregion
            list.Add(b2);
        }

        /// <summary>
        /// 映射
        /// </summary>
        /// <param name="c"></param>
        public virtual void YS(ConvertAssociate c)
        {
            PropertyMap mapMATERIALSID = new PropertyMap();//ID
            mapMATERIALSID.SourceProperty = "CODE";
            mapMATERIALSID.TargerProperty = "SourceCode";
            c.AddPropertyMap(mapMATERIALSID);

            PropertyMap map11 = new PropertyMap();//ID
            map11.SourceProperty = "p.ID";
            map11.TargerProperty = "SourceID";
            PropertyMap map12 = new PropertyMap();//ID
            map12.TargerProperty = "SourceController";
            map12.IsValue = true;
            map12.Value = this.ToString();

            PropertyMap map13 = new PropertyMap();//ID
            map13.SourceProperty = "ID";
            map13.TargerProperty = "SourceRowID";

            PropertyMap map14 = new PropertyMap();//ID
            map14.SourceProperty = "p.Code";
            map14.TargerProperty = "SourceCode";

            PropertyMap map15 = new PropertyMap();//ID
            map15.TargerProperty = "SourceName";
            map15.IsValue = true;
            map15.Value = ((IController)this).ControllerName();

            PropertyMap map16 = new PropertyMap();//ID
            map16.TargerProperty = "SourceTable";
            map16.IsValue = true;
            map16.Value = new StockOutNoticeMaterials().ToString();           

            c.AddPropertyMap(map11);
            c.AddPropertyMap(map12);
            c.AddPropertyMap(map13);
            c.AddPropertyMap(map14);
            c.AddPropertyMap(map15);
            c.AddPropertyMap(map16);
        }

        [WhereParameter]
        public string CustomId { get; set; }
        public string GetCustomerInfo()
        {
            string str = "";
            EntityList<ST_CustomerAdress> customerADList = new EntityList<ST_CustomerAdress>(this.model.GetDataAction());
           // EntityList<ST_Customer> customerList = new EntityList<ST_Customer>(this.model.GetDataAction());
           // customerList.GetData("id='" + CustomId + "'");
            customerADList.GetData("PID='" + CustomId + "'");
            if (customerADList.Count == 1) {
               // string LXRPhone = customerADList[0].LXRPhone;
               // string LXRAddress = customerADList[0].LXRAddress;

                str = JSON.Serializer(customerADList);
            }
            return str;
        }

        #endregion
        [ActionCommand(name = "查询库存详细", index = 1, isselectrow = true, ischild = true, childmodel = "Way.Bus.WMS.Model.StockOutNoticeMaterials")]
        public StockData GetStock()
        {
            StockData sd = new StockData();
            StockOutNoticeMaterials m = EntityHelper.ToEntity(this.Tag, typeof(StockOutNoticeMaterials)) as StockOutNoticeMaterials;
            if (m == null || string.IsNullOrEmpty(m.MATERIALCODE))
                throw new Exception("异常：货物不能为空！");
            if (m != null)
            {
                InitData data = new InitData();
                StockInfoMaterialsController.OnInitForeignStockInfoMaterials(new StockOutOrderMaterials(), data);
                foreach (ItemData d in data.modeldata.childitem)
                {
                    if (d.IsField("MCODE") || d.IsField("MNAME") || d.IsField("model"))
                        d.visible = false;
                    if (d.IsField("WNAME"))
                        d.visible = true;
                    if (d.IsField("SUBNO"))
                        d.title = "有效期";
                }
                sd.data = data;
                string sql = StockInfoView.GetStockSQL(0, 0, int.Parse(m.MATERIALCODE), 0, m.BATCHNO);
                IDataAction action = this.model.GetDataAction();
                DataTable table = action.GetDataTable(sql);
                foreach (DataColumn c in table.Columns)
                    c.ColumnName = c.ColumnName.ToUpper();
                sd.table = new ReadTable();
                sd.table.rows = table;
                sd.table.total = table.Rows.Count;
            }
            return sd;
        }
        public class StockData
        {
            public InitData data { get; set; }
            public ReadTable table { get; set; }
        }
    }
}
